import cv2
import requests
import numpy as np
import json
import tensorflow as tf
import os
from PIL import Image
from matplotlib import pyplot  as plt


SERVER_URL = 'http://192.168.1.211:8501/v1/models/porn_inceptionv4_tf_gpu:predict'
IMG_PATH = "./test_video/demo_porn/"
# IMG_PATH = "e:/datasets/mot/"


def processing_with_cv(img_file,central_fraction=0.875,show=False):
    img = cv2.imread(img_file)
    img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    img = cv2.resize(img,(299,299))#
    # print(img.shape)

    ## crop the image
    # w,h = img.shape[0],img.shape[1]
    # img = (img_resize / 255 - 0.5) / 2
    #
    # wd = int(w * central_fraction)
    # hd = int(h * central_fraction)
    # img = img[
    #     int((w - wd) / 2):int((w - wd) / 2 + wd),
    #     int((h - hd) / 2):int((h - hd) / 2 + hd),:


    if show:
        cv2.imshow("",img)
        cv2.waitKey(0)

    return img.reshape([1,299,299,3]).astype(np.int8)


def processing_with_pil(img_file,show=False,central_fraction=0.875,resize=()):
    img = Image.open(img_file)
    if resize:
        img = img.resize(resize)
    shape = img.size

    w,h = shape[0], shape[1]
    wd = w - int((w - w * central_fraction) / 2) * 2
    hd = h - int((h - h * central_fraction) / 2) * 2
    img = img.crop(((w-wd)/2,(h-hd)/2,(w-wd)/2+ wd, (h-hd)/ 2 + hd))  # left, up, right, below
    img = np.array(img)
    img_normal = (img / 255 - 0.5) / 2
    # img_normal = img_normal.astype(np.int8)
    if show:
        plt.imshow(img_normal)
        plt.show()
    return img_normal


def main():
    img_names_list = os.listdir(IMG_PATH)
    img_names_list.sort(key=lambda x:int(x.split('.')[0]))
    # print((img_names_list),img_names_list[0])



    processed_img = {}
    f = open("res/sj.txt", "a+")
    id =9294

    for img_file in range(23016,45531):#img_names_list:


        # if img_file.endswith('.jpeg') or img_file.endswith('.jpg') or img_file.endswith('.png'):
        #     img_file = IMG_PATH + img_file

            img_file = IMG_PATH + str(img_file) + '.jpg'

            print(img_file)
            # print(processing_with_pil(img_file))
            processed_img = processing_with_cv(img_file)
            data_dict = {"signature_name": "porn_detect", "inputs": processed_img.tolist()}
            data_dict = json.dumps(data_dict).encode("utf8")
            response = requests.post(SERVER_URL, data=data_dict)
            print(response.json())
            res = str(str(id) + ":" + img_file.split('/')[-1]) + " : " + str(
                response.json()["outputs"]["classes"][0][0]) + "---" + str(
                response.json()["outputs"]["scores"][0]) + '\n'
            id += 1
            if id == np.inf:
                break
            f.write(res)
            f.flush()
            print(res)
    f.close()

            # processed_img.append(processing_with_pil(img_file,))





if __name__ == '__main__':
    main()
    tf.zeros()